package vip.liux.front.application.listeners;

import com.github.benmanes.caffeine.cache.Cache;
import com.google.common.reflect.ClassPath;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplicationRunListener;
import org.springframework.context.ConfigurableApplicationContext;
import vip.liux.cache.GlobalCache;
import vip.liux.core.model.NameValue;

import java.io.IOException;
import java.time.Duration;
import java.util.Arrays;

import static vip.liux.front.infrastructure.constants.GlobalConstants.EnumsPackage;

public class EnumCacheListener implements SpringApplicationRunListener {

    private static final Logger log = LoggerFactory.getLogger(EnumCacheListener.class);
    private final Cache<String, Object> cache = GlobalCache.getCache("EnumCache", 0L);

    @Override
    public void started(ConfigurableApplicationContext context, Duration timeTaken) {
        try {
            for (String packageName : EnumsPackage) {
                ClassPath.from(ClassLoader.getSystemClassLoader())
                        .getTopLevelClassesRecursive(packageName)
                        .forEach(classInfo -> {
                            Class<?> clazz = classInfo.load();
                            if (clazz.isEnum()) {
                                Enum<?>[] enumConstants = (Enum<?>[]) clazz.getEnumConstants();
                                cache.put(clazz.getSimpleName(), Arrays.stream(enumConstants).map(e -> new NameValue<>(e.name(), e.ordinal())).toList());
                            }
                        });
            }

            log.info("Enums cache loaded success");
        } catch (IOException e) {
            log.warn("Enums cache load error", e);
        }
    }
}
